package com.hifar.test.entrust.controller;

import com.hifar.sys.BusiResponse;
import com.hifar.test.entrust.model.EntrustQRData;
import com.hifar.test.entrust.pojo.VO.HfEnvReportTaskVO;
import com.hifar.test.entrust.pojo.VO.HfEnvGkEntrustSaveVO;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.syncData.pojo.VO.SyncImportVO;
import com.hifar.test.test.service.IHfEnvTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 委托单 前端控制器 default
 * </p>
 *
 * @author wei
 * @since 2024-12-04 15:51:56
 */
@RestController
@RequestMapping("/api/busi/test/hfEnvGkEntrustController")
@Api(tags = "委托单功能")
public class HfEnvGkEntrustController {

    @Autowired
    private IHfEnvGkEntrustService gkEntrustService;
    @Autowired
    private IHfEnvTestService testService;

    private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    @PostMapping("/manualInputTask")
    @ApiOperation("手动新增任务")
    public BusiResponse manualInputTask(@RequestBody @Validated HfEnvGkEntrustSaveVO manualInputTaskVO) {
        gkEntrustService.manualInputTask(manualInputTaskVO);
        return BusiResponse.OK();
    }

    @ApiOperation("根据二维码新增任务")
    @PostMapping("/saveEntrustFromQRCode")
    public BusiResponse saveEntrustFromQRCode(@RequestBody EntrustQRData entrustQRData) {
        gkEntrustService.saveEntrustFromQRCode(entrustQRData);
        return BusiResponse.OK();
    }

    @ApiOperation("导入数据包")
    @PostMapping("/importDataPackage")
    public BusiResponse importDataPackage(@RequestBody @Validated SyncImportVO syncImportVO) {
        try {
            List<String> fileIds = syncImportVO.getFileIds();
            String fileId = syncImportVO.getFileId();
            
            // 优先使用fileIds数组，如果没有则使用fileId字符串
            if (fileIds != null && !fileIds.isEmpty()) {
                // 批量导入 - 使用数组格式
                List<String> validFileIds = fileIds.stream()
                        .filter(id -> id != null && !id.trim().isEmpty())
                        .map(String::trim)
                        .collect(java.util.stream.Collectors.toList());
                
                if (validFileIds.isEmpty()) {
                    return BusiResponse.error("没有有效的文件ID");
                }
                
                // 记录开始批量导入
                System.out.println("开始批量导入，文件数量: " + validFileIds.size());
                
                Map<String, Object> result = gkEntrustService.batchImportDataPackage(validFileIds);
                int successCount = (Integer) result.get("successCount");
                int failedCount = (Integer) result.get("failedCount");
                @SuppressWarnings("unchecked")
                List<String> errorMessages = (List<String>) result.get("errorMessages");
                
                // 详细调试信息
                System.out.println("=== 控制器接收到的结果 ===");
                System.out.println("成功数量: " + successCount);
                System.out.println("失败数量: " + failedCount);
                System.out.println("错误消息列表: " + errorMessages);
                System.out.println("错误消息数量: " + (errorMessages != null ? errorMessages.size() : 0));
                System.out.println("========================");
                
                // 记录导入结果
                System.out.println("批量导入完成，成功: " + successCount + ", 失败: " + failedCount);
                
                // 构建详细的返回信息
                StringBuilder responseMessage = new StringBuilder();
                responseMessage.append("导入完成：成功").append(successCount).append("个，失败").append(failedCount).append("个");
                
                if (failedCount > 0 && !errorMessages.isEmpty()) {
                    responseMessage.append("\n失败详情：");
                    for (int i = 0; i < errorMessages.size(); i++) {
                        responseMessage.append("\n").append(i + 1).append(". ").append(errorMessages.get(i));
                    }
                }
                
                String finalMessage = responseMessage.toString();
                System.out.println("返回消息: " + finalMessage);
                
                if (failedCount == 0) {
                    return BusiResponse.OK(finalMessage);
                } else if (successCount > 0) {
                    return BusiResponse.OK(finalMessage);
                } else {
                    return BusiResponse.error(finalMessage);
                }
            } else if (fileId != null && !fileId.trim().isEmpty()) {
                // 单个导入 - 兼容旧的字符串格式
                try {
                    gkEntrustService.importDataPackage(fileId.trim());
                    return BusiResponse.OK("导入成功");
                } catch (Exception e) {
                    return BusiResponse.error("导入失败: " + e.getMessage());
                }
            } else {
                return BusiResponse.error("请提供有效的文件ID");
            }
        } catch (Exception e) {
            System.err.println("导入过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return BusiResponse.error("导入过程中发生错误: " + e.getMessage());
        }
    }


    @GetMapping("/queryEntrustTaskList")
    @ApiOperation("查询委托下项目")
    public BusiResponse queryEntrustTaskList(@RequestParam("id") String gkEntrustId) {
        List<HfEnvReportTaskVO> taskList = gkEntrustService.queryEntrustTaskList(gkEntrustId);
        return BusiResponse.OK(taskList);
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "委托单功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam("id") String id) {
        HfEnvGkEntrustSaveVO byId = gkEntrustService.queryVOById(id);
        return BusiResponse.OK(byId);
    }

    @GetMapping("/existEntrustCode")
    @ApiOperation(value = "判断委托单号是否已存在")
    public BusiResponse existEntrustCode(@RequestParam("entrustCode") String entrustCode) {
        boolean exists = gkEntrustService.existEntrustCode(entrustCode);
        Assert.isTrue(!exists, "委托单号已存在");
        return BusiResponse.OK(exists);
    }

}